package cn.qiyu5522.service.impl;

import cn.qiyu5522.config.MinioProperties;
import cn.qiyu5522.constant.SystemConsKeys;
import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.domain.entity.SystemException;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.service.UploadService;
import cn.qiyu5522.utils.MinioUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class OssUploadService implements UploadService {

    @Resource
    private MinioUtils minioUtils;

    @Resource
    private MinioProperties minioProperties;

    @Override
    public ResponseResult uploadImg(MultipartFile img, String prefix) {
        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        int dotIndex = originalFilename.lastIndexOf('.');
        String extension="";
        if (dotIndex > 0) {
            extension = originalFilename.substring(dotIndex + 1);
        }
        // 可上传文件的后缀
        List<String> fileExt = minioProperties.getFileExt();
        //对原始文件名进行判断
        if(!fileExt.contains(extension)){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        // 创建并检查桶是否存在
        minioUtils.createBucket(minioProperties.getBucketName());
        // 设置桶策略 公开只读
        minioUtils.createBucketPolicy(SystemConsKeys.READ_ONLY_POLICY, minioProperties.getBucketName());
        // 上传文件
        Map<String, Object> stringObjectMap = minioUtils.uploadFile(minioProperties.getBucketName(),prefix, new MultipartFile[]{img});
        String bucketName = (String) stringObjectMap.get("bucketName");
        List<String> fileName = (List<String>) stringObjectMap.get("fileName");
        String filePath = fileName.get(0);
        return ResponseResult.okResult(minioProperties.getEndpoint()+"/"+bucketName+filePath);
    }

}